import {AfterContentInit, Component, ElementRef, EventEmitter, Input, Output, ViewChild} from '@angular/core';
import {DhlCommonComponent} from '../dhlCommonComponent';
import {DhlTableComponent} from '../table/dhl-table.component';
import {FormUtil} from '../../../utils/form-util';
import {ObjectUtil} from '../../../utils/object-util';

@Component({
  selector: 'dhl-query-location',
  templateUrl: './dhl-query-location.component.html'
})
export class DhlQueryLocationComponent extends DhlCommonComponent implements AfterContentInit {

  submitUrl;
  colWidthsNum;
  superColWidthsNum;
  buttonPositionTail;
  inputs = [];
  superInputs = [];
  buttonClassDiv = 'text-center';
  superQueryStyle = {display: 'none'};
  iconClass = ['super-query-icon'];
  iconDirection = 'caret-down';
  isHidden = true;
  showSuper = false;
  queryTitleClass = ['super-query-title'];

  @Input() set colWidths(value) {
    this.initCol(value);
  }

  @Input() showQueryBtn = true;
  @Input() showResetBtn = true;
  @Input() queryCheck;
  @Input() tableRef: DhlTableComponent;
  @ViewChild('dhlQueryConfig', {static: true, read: ElementRef}) dhlQueryConfig: ElementRef;
  @ViewChild('dhlQueryForm', {static: true, read: ElementRef}) dhlQueryForm: ElementRef;
  @ViewChild('dhlButton', {static: true, read: ElementRef}) dhlButton: ElementRef;
  @ViewChild('superQuery', {static: true, read: ElementRef}) superQueryRef: ElementRef;

  @Output() afterQuery = new EventEmitter();

  ngAfterContentInit(): void {


    if (this.router.url == '/report') {
      this.queryTitleClass.push('super-query-title-center');
    }

    if (!this.colWidthsNum) {
      this.initCol([[6, 6, 6, 6]]);
    }

    $(this.dhlQueryConfig.nativeElement).children().filter((i, p) => !$(p).is('dhl-query-actions')).each((index, item) => {
      this.inputs.push($(item));
    });
    $('dhl-super-query', this.dhlQueryConfig.nativeElement).children().each((index, item) => {
      this.superInputs.push($(item));
    });

    if (this.superInputs.length > 0) {
      this.showSuper = true;
    }

    const inter = setInterval(() => {
      const dhlcols = $('div[dhl-col]', $(this.dhlQueryForm.nativeElement));
      if (dhlcols.length > 0) {
        dhlcols.each((index, item) => {
          if (this.inputs[index]) {
            if (!this.inputs[index].is('dhl-super-query')) {
              $(item).append(this.inputs[index]);
            }
          }
        });
        if (this.superInputs.length > 0) {
          const dhlSuperCols = $('div[dhl-col]', $(this.superQueryRef.nativeElement));
          dhlSuperCols.each((index, item) => {
            if (this.superInputs[index]) {
              $(item).append(this.superInputs[index]);
            }
          });
        } else {
          $(this.superQueryRef.nativeElement).empty();
        }

        if (this.buttonPositionTail && this.superInputs.length == 0) {
          this.buttonClassDiv = 'text-left';
          const buttonDiv = $(this.dhlButton.nativeElement);
          buttonDiv.css('padding-left', '20px');
          $('div[dhl-col]:last', $(this.dhlQueryForm.nativeElement)).append(buttonDiv);
        }
        clearInterval(inter);
      }
    }, 100);

    this.initQueryButtons();

  }

  calculateColWidths(initColWidths, elementsLength) {

    if (elementsLength == 0) {
      return;
    }

    const colwidths = ObjectUtil.isUndefined(initColWidths) ? [[5, 5, 5, 5]] : [...initColWidths];
    const inputsNum = elementsLength;
    let colNumbers = 0;
    colwidths.forEach((row) => {
      colNumbers += row.length;
    });

    if (colNumbers < inputsNum) {
      const ns = (inputsNum - colNumbers) / colwidths[colwidths.length - 1].length;
      for (let i = 0; i < ns; i++) {
        colwidths.push(colwidths[colwidths.length - 1]);
      }
    }

    colNumbers = 0;
    colwidths.forEach((row) => {
      colNumbers += row.length;
    });

    const lastRow = [...colwidths[colwidths.length - 1]];
    const newLastRow = [];
    let totalTailWidth = 0;
    for (let i = 0; i < lastRow.length - (colNumbers - inputsNum); i++) {
      const col = lastRow[i];
      newLastRow.push(col);
      totalTailWidth += col;
    }
    newLastRow.push(24 - totalTailWidth);
    colwidths.pop();
    colwidths.push(newLastRow);

    const width = $('>div:first', this.dhlQueryForm.nativeElement).width();
    if ((24 - totalTailWidth) * width / 24 > 200) {
      this.buttonPositionTail = true;
    }
    return colwidths;
  }

  initCol(value) {
    if (!value) {
      return;
    }
    const queryElementsLength = $(this.dhlQueryConfig.nativeElement).children().filter((i, p) => !$(p).is('dhl-super-query')).length;
    const superQueryElementsLength = $('dhl-super-query', this.dhlQueryConfig.nativeElement).children().length;
    this.colWidthsNum = this.calculateColWidths(value, queryElementsLength);
    this.superColWidthsNum = this.calculateColWidths(value, superQueryElementsLength);
  }

  keyDown({code}) {
    if (code == 'Enter') {
      this.query();
    }
  }

  query() {
    const params = FormUtil.getData($(this.dhlQueryForm.nativeElement));
    let msg;
    if (this.queryCheck) {
      msg = this.queryCheck(params);
    }

    for (const action of this.tableRef.topButtonComponent) {
      action.queryParams = {...this.tableRef.defaultParams, ...params};
    }

    if (msg) {
      this.messageService.error(msg);
    } else {
      this.tableRef.fresh(params);
    }

    this.afterQuery.emit(params);
  }

  reset() {
    FormUtil.reset($(this.dhlQueryForm.nativeElement));

    if (this.tableRef) {
      for (const action of this.tableRef.topButtonComponent) {
        action.queryParams = this.tableRef.defaultParams;
      }
      this.tableRef.fresh({});
    }
  }

  superClick() {
    this.isHidden = !this.isHidden;
    if (this.isHidden) {
      this.iconDirection = 'caret-up';
    } else {
      this.iconDirection = 'caret-down';
    }
  }

  initQueryButtons() {
    const topActions = $('dhl-query-actions', this.dhlQueryConfig.nativeElement);
    $(this.dhlButton.nativeElement).append(topActions);
  }


}









